<template>
  <div class="wrapper">
    <div class="editName">
      <div class="header">
        <span class="return" @click="back()">返回</span>管理群
      </div>
    </div>
    <div @click="chyangeFaceUrl()" class="groupItem">
      <img :onerror="defGroupImg" :src="faceUrl" alt="">
      <div class="Set">选择头像<img src="../../assets/img/icon_shape@3x.png" alt=""></div>
    </div>
    <div class="myCard">
      <div class="lineWrapper">
        <div class="line"></div>
      </div>
      <router-link to="/ownerGroupDetailsSetName">
      <div class="myCardTitle">
        群名称
        <div class="notSet"><img src="../../assets/img/icon_shape@3x.png" alt=""></div>
      </div>
      </router-link>
    </div>
    <div v-show="groupData.TypeEn == 'Public' || groupData.TypeEn == 'ChatRoom'|| groupData.TypeEn == 'AVChatRoom'" class="selectedFriendsTitle">设置管理员</div>
     <router-link v-show="groupData.TypeEn == 'Public' || groupData.TypeEn == 'ChatRoom'|| groupData.TypeEn == 'AVChatRoom'" to="/ownerGroupAddManager">
    <div class="selectedFriends">
      <div class="friendList">
        <img  class="icon" src="../../assets/img/icon_group@3x.png" alt="">
        <div class="faceItem">
          <img v-for="(item,index) in groupPersons" :src="item.Tag_Profile_IM_Image" v-if="item.RoleEn == 'Admin' && index < 3" alt="">
          <img src="../../assets/img/icon_addfm@3x.png" alt="">
        </div>
      </div>
      <div class="Set">管理员{{managerNum()}}名<img src="../../assets/img/icon_shape@3x.png" alt=""></div>
    </div>
     </router-link>
    <div v-show="groupData.TypeEn == 'Public' || groupData.TypeEn == 'ChatRoom'|| groupData.TypeEn == 'AVChatRoom'" class="myCard">
      <div class="lineWrapper">
        <div class="line"></div>
      </div>
      <div class="myCardTitle">
        全局禁言
        <div class="btnWrapper">
          <mt-switch v-model="silent"></mt-switch>
          <div @click="changeSilent()" class="btnSilent"></div>
        </div>
      </div>
    </div>
    <div class="divisionLine"></div>
    <div class="myCard">
      <div class="lineWrapper">
        <div class="line"></div>
      </div>
      <div v-show="groupType == 'Public' || groupType == 'ChatRoom'" @click="showchangeTypeWrap()" class="myCardTitle">
        加群方式
        <div class="notSet">{{groupTypeDesc[ApplyJoinOption]}}<img src="../../assets/img/icon_shape@3x.png" alt=""></div>
      </div>
      <div v-show="groupType == 'Private'" class="myCardTitle">
        加群方式
        <div class="notSet">邀请加入<img src="../../assets/img/icon_shape@3x.png" alt=""></div>
      </div>
    </div>
    <div v-show="groupData.RoleEn" class="myCard">
      <div class="lineWrapper">
        <div class="line"></div>
      </div>
      <router-link to="/changeGroupOwner">
      <div class="myCardTitle">
        转让群
        <div class="notSet"><img src="../../assets/img/icon_shape@3x.png" alt=""></div>
      </div>
      </router-link>
    </div>
    <!-- 设置群组类型 -->
  <mt-actionsheet
    :actions="actionss"
    v-model="popup.changeTypeWrap">
  </mt-actionsheet>
  <!-- 设置群组类型 -->

    <!-- 底部菜单 -->
    <mt-actionsheet :actions="acti" v-model="sheetVisible"></mt-actionsheet>
    <!-- 文件上传-->
    <form id="uploadForm" ref="uploadForm">
      <input type="file" @change="changeFile" ref="uploadFileId">
    </form>
  </div>
</template>
<script>
import Client from '../../assets/js/common';
import { Popup } from 'mint-ui';
import { Actionsheet } from 'mint-ui';
import { MessageBox } from 'mint-ui';
import { Switch } from 'mint-ui';
import CosCloud from '../../../static/cos-js-sdk-v4'
import {axiosPost} from '../../assets/api'
import {Toast, Indicator} from 'mint-ui'
import {checkStatus} from '../../assets/js/login';
export default {
  data () {
    return {
      loginInfo: {},
      Introduction: '',
      groupPersons: [],
      groupMemberArr: [],
      groupData: {},
      defGroupImg: Client.defaultGroupImg,
      faceUrl: '',
      groupId:'',
      silent: false,
      ShutUpAllMember: '',
      groupType: "",
      groupTypeDesc: {'NeedPermission': '需要验证', 'DisableApply': '禁止加入', 'FreeAccess': '自由加入'}, // 加群方式
      // groupTypeDesc: {'Public': '需要验证', 'Private': '邀请加入', 'ChatRoom':'自由出入'},
      sheetVisible: false,
      ApplyJoinOption: "",
      acti:[
        {name: '相册', method: this.takePhoto},
      ],
      actionss: [
        {name: "自由出入", method: this.freeaccess},
        {name: "需要验证", method: this.needpermission},
        {name: "禁止加入", method: this.disableapply},
      ],
      popup: { 
          changeTypeWrap: false // 更换群组类型
        },
      cosdata: '',
      groupMsc: {},
      cos: ''
    }
  },
  created () {
    checkStatus((loginInfo) => {
      this.loginInfo = loginInfo;
      console.log("click",Client.getStore("ClickCurrentGroupData"));
      this.groupData = Client.getStore("ClickCurrentGroupData");
      this.faceUrl = this.groupData.FaceUrl
      this.groupId =  this.groupData.GroupId;
      this.Introduction = this.groupData.Introduction;
      this.ApplyJoinOption = this.groupData.ApplyJoinOption;
      this.groupType = this.groupData.TypeEn;
      this.groupMembers();
      this.initSilent();
    });
  },
  methods: {
    back() {
      history.back()
    },
    chyangeFaceUrl() {
      this.sheetVisible = true;
    },
    showchangeTypeWrap() {
      this.popup.changeTypeWrap = true;
    },
    // 拍照
      takePhoto(){
        this.$refs.uploadFileId.click();
      },
      freeaccess() {
      this.ApplyJoinOption = "FreeAccess";
      this.changeJoinType("FreeAccess");
      },
      needpermission() {
        this.ApplyJoinOption = "NeedPermission";
        this.changeJoinType("NeedPermission");
      },
      disableapply() {
        this.ApplyJoinOption = "DisableApply";
        this.changeJoinType("DisableApply");
      },
      // 上传头像
      changeFile(e){
        console.log(e);
        let That = this
        let apiname = "upload/uploadHeadPic";
        axiosPost({
          data: {
            "fileEtension": "jpg",
            "signType": 0
          },
          url: apiname + '?token=123&appSecret=8888',
          onSuccess (res) {
            That.cosdata = res.data.Result;
            console.log(That.cosdata)
            That.cos = new CosCloud({
              appid: That.cosdata.appid, // APPID 必填参数
              bucket: That.cosdata.bucket, // bucketName 必填参数
              region: That.cosdata.region, // 地域信息 必填参数 华南地区填gz 华东填sh 华北填tj
              getAppSign: function (callback) {
                callback(That.cosdata.AppSign);
              },//多次签名 可使用多次
              getAppSignOnce: function (callback) {
                 callback(That.cosdata.AppSignOnce);
              }
            });
            That.uploadFile(e)
          },
          onFailure (res) {
            console.log(res)
          }
        })
      },

      // 文件上传
      uploadFile(e){
        let That = this
        //let myFolder = 'head/';//需要操作的目录

        let successCallBack = function (result) {
          Indicator.close();
          if(result.code !== 0){
            Toast('图片上传失败');
            return;
          }else{
            let faceUrl = result.data.access_url;
            //console.log(That.faceUrl);
            That.faceUrl = faceUrl;
            That.changeGroupUrl(faceUrl);
          }
        };
        
        let errorCallBack = function (result) {
          Indicator.close()
          result = result || {};
          console.log('request error:', result && result.message);
        };


        let progressCallBack = function (curr, sha1) {
          let sha1CheckProgress = ((sha1 * 100).toFixed(2) || 100) + '%';
          let uploadProgress = ((curr || 0) * 100).toFixed(2) + '%';
          let msg = 'upload progress:' + uploadProgress + '; sha1 check:' + sha1CheckProgress + '.';
          // if (uploadProgress === '100.00%') {
          //   Indicator.close();
          //   Toast('图片上传成功')
          //   // _this.isSet = true
          // }
        };

        let lastTaskId;
        let taskReady = function (taskId) {
          lastTaskId = taskId;
        };
        let file = e.target.files[0];
        let fileLimit = 1024 * 1024 * 20   // 1M图片限制
        if (!file.type.includes('image')) {
          Toast("请上传图片格式的文件")
          this.$refs.uploadForm.reset()
          return false
        }
        if (file.size > fileLimit) {
          Toast('请上传20M以内的图片')
          this.$refs.uploadForm.reset()
          return false
        }
        // 分片上传过程可能会有 op=upload_slice_list 的 POST 请求返回 404，不会影响上传
        Indicator.open();
        this.cos.uploadFile(successCallBack, errorCallBack, progressCallBack, this.cosdata.bucket,
          this.cosdata.fileName, file, 0, taskReady);//insertOnly==0 表示允许覆盖文件 1表示不允许
        return false;
      },
    managerNum(){
      let num = 0;
      console.log("wshnjklfsjkdl",this.groupPersons);
      for( let i = 0; i < this.groupPersons.length; i++) {
         if(this.groupPersons[i].RoleEn == 'Admin') {
           num++;
         }
      }
      return num;

    },
    changeSilent() {
      if(this.silent){
        this.silent = false;
        this.ShutUpAllMember = 'Off';
      }else{
        this.silent = true;
        this.ShutUpAllMember = 'On';
      }
       this.changeShutUpAllMember();
    },
    initSilent() {
      let isOff = this.groupData.ShutUpAllMember
      if(isOff == 'Off'){
        this.silent = false;
      }else{
        this.silent = true;
      }
    },
    changeShutUpAllMember() {
      //修改群全局禁言
        let options = {
            'GroupId': this.groupId,
            'ShutUpAllMember': this.ShutUpAllMember,
        };
          webim.modifyGroupBaseInfo(
                options,
                (resp) => {
                    Toast('修改群资料成功');
                    this.changeStorage('ClickCurrentGroupData', 'ShutUpAllMember', this.ShutUpAllMember, null);
                },
                (err) => {
                    alert(err.ErrorInfo);
                }
        );  
    },
    changeJoinType(type) {
      //修改群全局禁言
        let options = {
            'GroupId': this.groupId,
            'ApplyJoinOption': type,
        };
        
          webim.modifyGroupBaseInfo(
                options,
                (resp) => {
                    Toast('修改群资料成功');
                    this.changeStorage('ClickCurrentGroupData', 'ApplyJoinOption', type, null);
                },
                (err) => {
                    Client.errInfo;
                    console.log(err.ErrorInfo);
                }
        );  
    },
    // 修改群组头像
    changeGroupUrl(Url) {
      
        let options = {
            'GroupId': this.groupId,
            'FaceUrl': Url,
        };
          webim.modifyGroupBaseInfo(
                options,
                (resp) => {
                    Toast('修改群资料成功');
                    this.changeStorage('ClickCurrentGroupData', 'FaceUrl', Url, null);
                },
                (err) => {
                    alert(err.ErrorInfo);
                }
        );  
    },
    // 获取当前群组成员
      groupMembers() {
						let options = {
								'GroupId': this.groupId,
								'Offset': 0, // 必须从0开始
								'Limit': 2000,
								'MemberInfoFilter': [
										'Account',
										'Role',
										'JoinTime',
										'LastSendMsgTime',
                    'ShutUpUntil',
								]
						};
						webim.getGroupMemberInfo(
								options,
								(resp) => {
										if (resp.MemberNum <= 0) {
                        // alert('该群组目前没有成员');
                        Client.errInfo();
												return;
										}
                    let data = [];
                    let ids = [];
										for (let i in resp.MemberList) {
                        let account = resp.MemberList[i].Member_Account;
												let role = webim.Tool.groupRoleEn2Ch(resp.MemberList[i].Role);
												let part = resp.MemberList[i].Role;
												let join_time = webim.Tool.formatTimeStamp(resp.MemberList[i].JoinTime);
												let shut_up_until = webim.Tool.formatTimeStamp(resp.MemberList[i].ShutUpUntil);
												if (shut_up_until == 0) {
														shut_up_until = '-';
												}
												ids.push(account);
												data.push({
														GId: this.groupId,
														GroupId:  webim.Tool.formatText2Html(this.groupId),
														Member_Account: webim.Tool.formatText2Html(account),
														Role: role,
														JoinTime: join_time,
														ShutUpUntil: shut_up_until,
														Part: part
                        });
                        
                    }
                    this.groupMemberArr = data;

                    Client.log("群成员列表数据-start");
                    console.log(1111,this.groupMemberArr,ids);
                    this.getpersonData(ids);
                    Client.log("群成员列表数据-start");

										// $('#get_group_member_table').bootstrapTable('load', data);
										// $('#get_group_member_dialog').modal('show');
								},
								(err) => {
										alert(err.ErrorInfo);
								}
						);
        },
        // 个人资料列表
			getpersonData(ids) {
					let tag_list = [
							"Tag_Profile_IM_Nick", // 昵称
							"Tag_Profile_IM_Image", // 头像URL
					];
					let options = {
							'To_Account': ids,
							'TagList': tag_list
					};
					webim.getProfilePortrait(
							options,
							(resp) => {

									 if (resp.UserProfileItem && resp.UserProfileItem.length > 0) {
                     console.log(333,resp);
                     let data = [];
                     for(let i = 0; i < resp.UserProfileItem.length; i++){
                       let obj =  {};
                        obj["To_Account"] = resp.UserProfileItem[i].To_Account;
                       for(let j = 0; j < resp.UserProfileItem[i].ProfileItem.length; j++){
                         obj[resp.UserProfileItem[i].ProfileItem[j].Tag] = resp.UserProfileItem[i].ProfileItem[j].Value
                       }
                       for(let k = 0; k < this.groupMemberArr.length; k++){
                         if(obj["To_Account"] == this.groupMemberArr[k].Member_Account) {
                           obj["RoleEn"] = this.groupMemberArr[k].Part;
                         }
                       }
                      
                       data.push(obj);
                    }
                      this.groupPersons = data;
                       console.log("women",this.groupPersons);

									  }
							},
							(err) => {
                  // alert(err.ErrorInfo);
                  Client.errInfo();
							}
					);
					// $('#set_profile_portrait_dialog').modal('show');
      },

    save() {
      //修改群资料
        if (webim.Tool.getStrBytes(this.Introduction) > 150) {
            Toast('您输入的群组简介超出限制(最长50个汉字)');
            return;
        }
        let options = {
            'GroupId': this.groupId,
            'Introduction': this.Introduction,
        };
          webim.modifyGroupBaseInfo(
                options,
                (resp) => {
                    Toast('修改群资料成功');
                    this.changeStorage('ClickCurrentGroupData', 'Introduction', this.Introduction, null);
                    this.back();

                },
                (err) => {
                    alert(err.ErrorInfo);
                }
        );  
    },

    changeStorage(storeName, field, changeData, save) {
       let createData = Client.getStore(storeName);
       if(!createData) return;
       createData[field] = changeData;
       Client.setStore(storeName, createData);
       if(save) {
         save = Client.getStore(storeName);
       }
    },
  },
  components: {
    'mtSwitch': Switch 
  }
}
</script>
<style>
  /* .mint-switch-core {
    background-color: red;
        border-color: #26a2ff;
    background-color: #26a2ff;
  } */
  .mint-switch-input:checked + .mint-switch-core {
    border-color: #E5E5E5;
    background-color: #E5E5E5;
  }
</style>

<style lang="less" scoped>
#uploadForm {
  height: 0;
  overflow: hidden;
}
.editName{
        width: 100%;
        height: 100%;
        background: #F5F5F5;
        .setNameLine {
          height: 0.21rem;
        }
        .input {
          width: 100%;
          height: 0.5rem;
          text-indent: 0.15rem;
          background-color: white;
          color: #4A4A4A;
          font-size: 0.14rem;
          outline: none;
          font-weight: 400;
          border: none;
        }
      }
  .wrapper {
    .selectedFriends {
      height: 0.7rem;
      display: flex;
      justify-content: space-between;
      padding: 0 0.15rem;
      background-color: white;
      align-items: center;
      .friendList{
        display: flex;
        align-items: center;
        .icon {
          width: 0.20rem;
          height: 0.20rem;
          margin-right: 0.1rem;
        }
        .faceItem {
          img {
            width: 0.5rem;
            height: 0.5rem;
            float: left;
            border-radius: 50%;
            margin-right: 0.1rem;
          }
        }
      }
      .Set {
          display: flex;
          align-items: center;
          font-size: 0.12rem;
          img {
            width: 0.15rem;
            height: 0.15rem;
            margin: 0;
          }
      }
    }
    .selectedFriendsTitle {
        height: 0.27rem;
        line-height: 0.27rem;
        background-color: #F4F4F4;
        padding: 0 0.15rem;
        color:#818181;
        font-size: 0.12rem;
    }
    .divisionLine {
      height: 0.1rem;
      background-color: #F4F4F4;
    }
    .groupItem {
      height: 0.8rem;
      padding: 0.15rem;
      display: flex;
      background-color: white;
      position: relative;
      justify-content: space-between;
      box-sizing: border-box;
      .Set {
          display: flex;
          align-items: center;
          font-size: 0.12rem;
          img {
            width: 0.15rem;
            height: 0.15rem;
            margin: 0;
          }
      }
      .icon {
        width: 0.15rem;
        height: 0.15rem;
        position: absolute;
        right: 0.15rem;
        top: 50%;
        margin-top: -0.07rem;
      }
      img {
        width: 0.5rem;
        height: 0.5rem;
        border-radius: 50%;
        margin: 0 0.1rem 0 0;
      }
    }
    .header {
      width: 3.75rem;
      height: 0.5rem;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      font-size: 0.16rem;
      border-bottom: 1px solid #f4f4f4;
      background-color: white!important;
      .return {
        color: #4A4A4A;
        font-size: 0.16rem;
        position: absolute;
        left: 0.15rem;
      }
      .send {
        color: #4A4A4A;
        font-size: 0.16rem;
        position: absolute;
        right: 0.15rem;
      }
    }
    .myCard {
      height: 0.51rem;
      background-color: white;
      padding: 0 0.15rem;
      .lineWrapper {
        height: 1px;
        .line {
          width: 3.45rem;
          height: 1px;
          background-color: #E5E5E5;
        }
      }
      .myCardTitle {
        height: 0.5rem;
        line-height: 0.5rem;
        display: flex;
        justify-content: space-between;
        font-size: 0.14rem;
        color: #4a4a4a;
        .btnWrapper {
          display: flex;
          align-items: center;
          position: relative;
          .btnSilent {
            position: absolute;
            width:100%;
            height: 100%;
            z-index: 100;
          }
        }
        .manageItem {
          display: flex;
          align-items: center;
          img {
            width: 0.2rem;
            height: 0.2rem;
            margin-right: 0.1rem;
          }
        }
        .notSet {
          display: flex;
          align-items: center;
          img {
            width: 0.15rem;
          }
        }
      }
      .line {
        height: 1px solid #E5E5E5;
      }
    }
    
  }

</style>

